/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package rs_GUI;

import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import javax.persistence.EntityManager;
import javax.swing.JOptionPane;
import pojos.Album;
import pojos.Artist;
import pojos.Musicgenre;
import pojos.Musicgroup;
import pojos.Musicproductioncompany;
import java.util.Date;
import java.util.List;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import pojos.Playlist;
import pojos.Song;

/**
 *
 * @author Mastroperrou
 */

public class GroupAlbum_MainPanel extends javax.swing.JPanel {
    
    private RadioStationParentFrame frame;
    private EntityManager em;
    private Musicgenre mus;
    private int row;
    private Artist artist;
    private Musicgroup group;
    private int x;
    private String neoAlbum = "";
    private String neoAlbumType = "cs";
    private int diskNr = 1;
    private Date neaDate = new Date();
    private boolean cancelSave = false; //Το θέτουμε true όταν πατάμε το κουμπί μεταβολή, ενω
                                        //το θέτουμε false όταν πατάμε το κουμπί εισαγωγή
    
    JMenuBar menu = new JMenuBar();
    JMenu  jMenu1 = new JMenu("Μενού"); 
    
    /**
     * Creates new form WelcomeJPanel
     */
    public GroupAlbum_MainPanel(RadioStationParentFrame frame, EntityManager em) {
        this.frame = frame;
        this.em = em;
        initComponents();
        
        //Ταξινόμηση της artistList
        sortAlbumList();
    
    JMenuItem newGroupItem = new JMenuItem("Εισαγωγή Νέου");
        newGroupItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newGroupItemActionPerformed(evt);
            }
        });
        jMenu1.add(newGroupItem);
              
        JMenuItem exitItem = new JMenuItem("Έξοδος");
        exitItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitItemActionPerformed(evt);
            }
        });
        jMenu1.add(exitItem);
               
        menu.add(jMenu1);
        frame.setJMenuBar(menu);
    }
    
    private void newGroupItemActionPerformed(java.awt.event.ActionEvent evt) {                                           
        this.newButtonActionPerformed(evt);
    }      
     
    private void exitItemActionPerformed(java.awt.event.ActionEvent evt) {                                           
        this.exitButtonActionPerformed(evt);
    }
    
    //Ταξινόμηση της albumList
    private void sortAlbumList(){
        Collections.sort(albumList, new Comparator<Album>() {
            @Override 
            public int compare(Album al1, Album al2) {
                return al1.getTitle().compareTo(al2.getTitle());
            }
        });
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        albumQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT a FROM Album a WHERE a.musicgroupid IS NOT null");
        albumList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(albumQuery.getResultList());
        album1 = new pojos.Album();
        productionCompanyQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT pc FROM Musicproductioncompany pc");
        productionCompanyList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : productionCompanyQuery.getResultList();
        newButton = new javax.swing.JButton();
        changeButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        albumTable = new javax.swing.JTable();
        mainLabel = new javax.swing.JLabel();
        exitButton = new javax.swing.JButton();

        setPreferredSize(new java.awt.Dimension(610, 445));

        newButton.setText("ΕΙΣΑΓΩΓΗ");
        newButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newButtonActionPerformed(evt);
            }
        });

        changeButton.setText("ΜΕΤΑΒΟΛΗ");
        changeButton.setMaximumSize(new java.awt.Dimension(113, 23));
        changeButton.setMinimumSize(new java.awt.Dimension(113, 23));
        changeButton.setPreferredSize(new java.awt.Dimension(113, 23));
        changeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeButtonActionPerformed(evt);
            }
        });

        deleteButton.setText("ΔΙΑΓΡΑΦΗ");
        deleteButton.setMaximumSize(new java.awt.Dimension(113, 23));
        deleteButton.setMinimumSize(new java.awt.Dimension(113, 23));
        deleteButton.setPreferredSize(new java.awt.Dimension(113, 23));
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        albumTable.setFont(new java.awt.Font("Comic Sans MS", 1, 13)); // NOI18N

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, albumList, albumTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${title}"));
        columnBinding.setColumnName("Τίτλος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${musicgroupid}"));
        columnBinding.setColumnName("Group");
        columnBinding.setColumnClass(pojos.Musicgroup.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${musicproductioncompanyid}"));
        columnBinding.setColumnName("Εταιρεία Παραγωγής");
        columnBinding.setColumnClass(pojos.Musicproductioncompany.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        albumTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                albumTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(albumTable);
        if (albumTable.getColumnModel().getColumnCount() > 0) {
            albumTable.getColumnModel().getColumn(2).setPreferredWidth(0);
        }

        mainLabel.setText("ΠΙΝΑΚΑΣ ΑΛΜΠΟΥΜ ΣΥΓΚΡΟΤΗΜΑΤΩΝ");

        exitButton.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
        exitButton.setText("ΕΞΟΔΟΣ");
        exitButton.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(mainLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(newButton, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(deleteButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(changeButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(exitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 567, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 21, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(mainLabel)
                .addGap(13, 13, 13)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 339, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(exitButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(newButton, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(deleteButton, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(changeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(23, 23, 23))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {changeButton, deleteButton, exitButton, newButton});

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents
       
    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
        x = 2;    
        //Δημιουργούμε ένα νέο άλμπουμ
        album1 = new Album (null, neoAlbum, neoAlbumType, diskNr);
        album1.setMusicproductioncompanyid((Musicproductioncompany)productionCompanyList.get(0));
        album1.setReleasedate(neaDate);
        
        try {
            //Νέα δοσοληψία
            if (!em.getTransaction().isActive()) {
                em.getTransaction().begin();
            //Κάνε persist το album1 στη ΒΔ   
            em.persist(album1);
            //Ρίχτο στη ΒΔ
            em.flush();
            
            }
        }catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "Σφάλμα βάσης...");
        }
        cancelSave = false;
        frame.addPanelInMain(new AlbumManagement(frame, em, album1, x, cancelSave));
        
    }//GEN-LAST:event_newButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        // Βάζουμε στη μεταβλητή row τη γραμμή που επιλέξαμε
        row = albumTable.getSelectedRow();
        
        // Αν δεν έχουμε επιλλέξει κάτι τότε βγάλε μήνυμα λάθους
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "Επιλέξτε ένα άλπμουμ.", 
                                           "ERROR",
                                           JOptionPane.WARNING_MESSAGE);
        }
        
        else {
            // Μήνυμα επιβεβαίωσης της διαγραφής
            Object[] options = {"Ναι","Όχι"};
            Integer choice = JOptionPane.showOptionDialog(this,
            "Διαγραφή επιλεγμένου άλμπουμ;",
            "Επιβεβαίωση διαγραφής",
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            options,
            options[0]);
            
            if (choice == JOptionPane.YES_OPTION){
                changeButton.setEnabled(false);
                //Βάλε στο album1 τον άλμπουμ
                album1 = albumList.get(row);
                
                try {
                    //Νέα δοσοληψία
                    if (!em.getTransaction().isActive()) {
                        em.getTransaction().begin();
                    }
                    
                    //Αφαιρούμε τα τραγούδια του album1 από τις λίστες στις
                    //οποίες πιθανώς να ανήκουν
                    for(Song sn : album1.getSongList()){
                        //Εντοπίζουμε το τραγούδι στη βάση από το id του
                        Song s2 = em.find(Song.class, sn.getId());
                        // Το διαγράφουμε από τις λίστες στις οποίες πιθανον να ανήκε
                        for (Playlist pl : s2.getPlaylistList()) { 
                            pl.getSongList().remove(sn);
                        }
                    }
                    //Αφαιρούμε τα τραγούδια του album1 από τη ΒΔ
                    for(Song s : album1.getSongList()){
                        em.remove(s);
                    }
                    //Αφαιρούμε το album1 από τη βάση
                    em.remove(album1);
                    //Διαγράφουμε το album από τη λίστα με τους καλλιτέχνες
                    //που υπάρχει στον κώδικα της φόρμας
                    albumList.remove(album1);
                           
                    //Τερματισμός δοσοληψίας
                    em.getTransaction().commit();
                    } catch (Exception e) {
                        e.printStackTrace();
                        JOptionPane.showMessageDialog(null, "Σφάλμα βάσης...");
                    }
                
                artist = album1.getArtistid();
                if (album1.getArtistid() != null){
                    artist.getAlbumList().remove(album1);
                }
                
                group = album1.getMusicgroupid();
                if (album1.getMusicgroupid() != null){
                   group.getAlbumList().remove(album1);
                }
                    
                changeButton.setEnabled(true); 
            }
        }
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void changeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeButtonActionPerformed
        // Βάζουμε στη μεταβλητή row τη γραμμή που επιλέξαμε
        row = albumTable.getSelectedRow();
        
        // Αν δεν έχουμε επιλλέξει κάτι τότε βγάλε μήνυμα λάθους
        if (albumTable.getSelectedRow() == -1) {
            JOptionPane.showMessageDialog(this, "Επιλέξτε ένα άλμπουμ.", 
                                           "ERROR",
                                           JOptionPane.WARNING_MESSAGE);
        }
        
        else {
            cancelSave = true;
            //Βάλε στο album1 το επιλεγμένο άλμπουμ.
            album1 = albumList.get(row);
            //Κάνε τον persist στη ΒΔ
            em.persist(album1);
            x = 2;
            frame.addPanelInMain(new AlbumManagement(frame, em, album1, x, cancelSave));
        }
    }//GEN-LAST:event_changeButtonActionPerformed

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        frame.addPanelInMain(new EmptyMainPanel(frame));
        frame.addPanelInSide(new MainMenuSidePanel(frame, em));
    }//GEN-LAST:event_exitButtonActionPerformed

    private void albumTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_albumTableMouseClicked
        if(evt.getClickCount()==2){
            ActionEvent e = null;
            changeButtonActionPerformed(e);
        }
    }//GEN-LAST:event_albumTableMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private pojos.Album album1;
    private java.util.List<pojos.Album> albumList;
    private javax.persistence.Query albumQuery;
    private javax.swing.JTable albumTable;
    private javax.swing.JButton changeButton;
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton exitButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel mainLabel;
    private javax.swing.JButton newButton;
    private java.util.List<pojos.Musicproductioncompany> productionCompanyList;
    private javax.persistence.Query productionCompanyQuery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
